import cv2
import dlib
import matplotlib.pyplot as plt
from timecacu import getTimer

# 2 方法：显示图片
def show_image(image, title):
    img_RGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    plt.title(title)
    plt.imshow(img_RGB)
    plt.axis("off")

# 3 绘制人脸矩形
def plot_rectangle(image, faces,scale=4):
    for face in faces:
        cv2.rectangle(image, (face.left()*scale, face.top()*scale), (face.right()*scale, face.bottom()*4), (255, 0, 0), 2)
    return image

#http://dlib.net/files/  下载人脸关键点
#实时检测，性能不错

def captureFaceVideo(video,scale=4):
    # 打开摄像头
    cap = cv2.VideoCapture(video)
    detector = dlib.get_frontal_face_detector()
    t = getTimer("dlib_rec")
    print("打印摄像头采集的帧的尺寸")
    print(cap.get(cv2.CAP_PROP_FRAME_WIDTH), cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    while True:
        # 读取视频帧
        ret, frame = cap.read()
        t.start()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        gray = cv2.resize(gray, (0, 0), fx=1.0 / scale, fy=1.0 / scale)
        # 进行人脸检测
        dets_result = detector(gray, 1)  # 1: 将图片放大一倍
        t.end()

        img_result = plot_rectangle(frame.copy(), dets_result,scale)

        # 显示结果

        cv2.imshow('Face Detection', img_result)
        # 按下q键退出
        if cv2.waitKey(1) == ord('q'):
            break
    t.show()
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    captureFaceVideo(0)